package vworld.business.connection;

import generated.business.connection.ConnectionServicePOA;
import generated.business.connection.ExistUserException;
import generated.callback.ClientCallback;
import generated.domain.user.User;

import java.util.Map;

import org.omg.CORBA.ORB;

import vworld.ServerSingleton;

public class ConnectionServiceServant extends ConnectionServicePOA {

	private ORB orb;
	private User user;

	public void setOrb(ORB pOrb) {
		orb = pOrb;
	}

	public boolean login(String login, String password)
			throws ExistUserException {
		User lUser = ServerSingleton.getInstance().USER_DAO.getUser(login,
				password);

		if (lUser != null) {
			if (!isAlreadyConnected(lUser)) {
				user = lUser;
			} else {
				throw new ExistUserException(
						"The user is alreday connected.");
			}
			return true;
		}
		return false;
	}

	private boolean isAlreadyConnected(User user) {
		for (Map.Entry<String, ClientCallback> e : ServerSingleton
				.getInstance().REGISTERED_CLIENT_MAP.entrySet()) {
			if (e.getKey().equals(user.getLogin())) {
				return true;
			}
		}
		return false;
	}

	public boolean logout(ClientCallback clientRef) {
		deRegisterClient(clientRef.userLogin(), clientRef);

		// update admin connected users view
		for (ClientCallback cl : ServerSingleton.getInstance()
				.getAdminCallBackList()) {
			cl.doNotifyOnUserConnection();
		}

		return true;
	}

	public User getConnectedUser() {
		return user;
	}

	public boolean registerClient(String userLogin, ClientCallback client) {
		ClientCallback cl = ServerSingleton.getInstance().REGISTERED_CLIENT_MAP
				.put(userLogin, client);

		// update connected users view
		for (ClientCallback clc : ServerSingleton.getInstance()
				.getAdminCallBackList()) {
			clc.doNotifyOnUserConnection();
		}

		return cl != null ? true : false;
	}

	public boolean deRegisterClient(String userLogin, ClientCallback client) {
		ClientCallback cl = ServerSingleton.getInstance().REGISTERED_CLIENT_MAP
				.remove(userLogin);
		return cl != null ? true : false;
	}
}
